﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace SSHTool.Core
{
    public class RichTextBoxHelper : DependencyObject
    {
        public static string GetRichText(DependencyObject obj)
        {
            return (string)obj.GetValue(RichTextProperty);
        }

        public static void SetRichText(DependencyObject obj, string value)
        {
            obj.SetValue(RichTextProperty, value);
        }

        public static readonly DependencyProperty RichTextProperty = DependencyProperty.RegisterAttached("RichText", typeof(string), typeof(RichTextBoxHelper), new FrameworkPropertyMetadata
        {
            BindsTwoWayByDefault = true,
            PropertyChangedCallback = (obj, e) =>
            {
                var richTextBox = (RichTextBox)obj;
                var text = GetRichText(richTextBox);
                richTextBox.AppendText(text);
                richTextBox.AppendText(Environment.NewLine);
                richTextBox.ScrollToEnd();
            }
        });

        public static bool GetClearFlag(DependencyObject obj)
        {
            return (bool)obj.GetValue(ClearFlagProperty);
        }

        public static void SetClearFlag(DependencyObject obj, bool value)
        {
            obj.SetValue(ClearFlagProperty, value);
        }

        public static readonly DependencyProperty ClearFlagProperty = DependencyProperty.RegisterAttached("ClearFlag", typeof(bool), typeof(RichTextBoxHelper), new FrameworkPropertyMetadata()
        {
            BindsTwoWayByDefault = true,
            PropertyChangedCallback = (obj, e) =>
            {
                var richTextBox = (RichTextBox)obj;
                var flag = GetClearFlag(richTextBox);
                if (flag)
                {
                    richTextBox.Document.Blocks.Clear();
                }
            }
        });
    }
}
